package com.iot.aliyun.utils;


import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.iot.aliyun.handler.ResultHandler;
import com.iot.commonutils.utils.Result;
import org.springframework.stereotype.Component;

import java.util.List;


//设备管理工具类
@Component
public class DeviceUtil {
    //公共参数

    String regionId="cn-shanghai";//注册地ID

    String accessKeyId="LTAI4G2LfkTureHi7wPqy6Sv";

    String secret="7nv340IB0cPz776aphznfuNrpxAUXM";

    String iotInstanceId;//企业实例ID

    String sysDomain="iot."+regionId+".aliyuncs.com";//系统域名

    String sysVersion="2018-01-20";//系统版本


    /**
     * 调用该接口在指定产品下注册设备
     *
     * @param ProductKey    产品的唯一标识
     * @param DeviceName    设备名称（如果不传入，阿里云平台自动生成）
     * @param DevEui        LoRaWAN设备的DevEUI（创建LoRaWAN设备时，该参数必传）
     * @param PinCode       LoRaWAN设备的PIN Code，用于校验DevEUI的合法性（创建LoRaWAN设备时，该参数必传）
     * @param Nickname      待注册的设备设置备注名称（如果不传入，系统不会生成备注名称）
     * @return
     */
    public Result RegisterDevice(String ProductKey, String DeviceName, String DevEui,
                                 String PinCode, String Nickname) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(sysDomain);
        request.setSysVersion(sysVersion);
        request.setSysAction("RegisterDevice");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey", ProductKey);
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        request.putQueryParameter("DeviceName", DeviceName);
        request.putQueryParameter("DevEui", DevEui);
        request.putQueryParameter("PinCode", PinCode);
        request.putQueryParameter("Nickname", Nickname);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return  ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口查询指定设备的详细信息
     *
     * @param ProductKey    要查询的设备所属产品的唯一标识（如果传入该参数，需同时传入DeviceName）
     * @param DeviceName    指定要查询的设备名称（如果传入该参数，需同时传入ProductKey）
     * @param IotId         设备的唯一标识（如果传入此参数，则无需传入ProductKey和DeviceName。如果都传入，以IotId为准）
     * @return
     */
    public Result QueryDeviceDetail(String ProductKey, String DeviceName, String IotId) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("QueryDeviceDetail");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        request.putQueryParameter("ProductKey", ProductKey);
        request.putQueryParameter("DeviceName", DeviceName);
        request.putQueryParameter("IotId", IotId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口批量查询某一产品下设备详情
     *
     * @param DeviceNames   要查询的设备名称列表
     * @param ProductKey    设备所属产品的唯一标识
     * @return
     */
    public Result BatchQueryDeviceDetail(List<String> DeviceNames, String ProductKey) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("BatchQueryDeviceDetail");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey", ProductKey);
        if (DeviceNames != null) {
            for (int i = 0; i < DeviceNames.size(); i++) {
                System.out.println(i);
                request.putQueryParameter("DeviceName." + (i + 1), DeviceNames.get(i));
            }
        }
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口查询指定产品下的所有设备列表
     *
     * @param ProductKey    要查询的设备所属产品的唯一标识
     * @param PageSize      指定返回结果中每页显示的记录数量（最大值是50，默认是10）
     * @param CurrentPage   指定显示返回结果中的第几页内容（默认第一页）
     * @return
     */
    public Object QueryDevice(String ProductKey,Integer PageSize, Integer CurrentPage) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("QueryDevice");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("ProductKey", ProductKey);
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        request.putQueryParameter("PageSize", PageSize.toString());
        request.putQueryParameter("CurrentPage", CurrentPage.toString());
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误").toString();
    }

    /**
     * 调用该接口删除指定设备
     *
     * @param IotId         设备的唯一标识（如果传入此参数，则无需传入ProductKey和DeviceName。如果都传入，以IotId为准）
     * @param ProductKey    要查询的设备所属产品的唯一标识（如果传入该参数，需同时传入DeviceName）
     * @param DeviceName    指定要查询的设备名称（如果传入该参数，需同时传入ProductKey）
     * @return
     */
    public Result DeleteDevice(String IotId, String ProductKey, String DeviceName) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("DeleteDevice");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        request.putQueryParameter("ProductKey", ProductKey);
        request.putQueryParameter("DeviceName", DeviceName);
        request.putQueryParameter("IotId", IotId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口查看指定设备的运行状态
     *
     * @param IotId         要查看设备的id（如果传入此参数，则无需传入ProductKey和DeviceName。如果都传入，以IotId为准）
     * @param ProductKey    要查看的设备所属产品的唯一标识（如果传入该参数，需同时传入DeviceName）
     * @param DeviceName    要查看设备的名称（如果传入该参数，需同时传入ProductKey）
     * @return
     */
    public Result GetDeviceStatus(String IotId, String ProductKey, String DeviceName) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("GetDeviceStatus");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        request.putQueryParameter("ProductKey", ProductKey);
        request.putQueryParameter("DeviceName", DeviceName);
        request.putQueryParameter("IotId", IotId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口批量查看同一产品下指定设备的运行状态（单次最多查询50个设备）
     *
     * @param DeviceNames   要查看运行状态的设备的名称列表（如果传入该参数，需同时传入ProductKey）
     * @param ProductKey    要查看运行状态的设备所隶属的产品的唯一标识（如果传入该参数，需同时传入DeviceName）
     * @param IotIds        要查看运行状态的设备唯一标识的列表（如果传入此参数，则无需传入ProductKey和DeviceName。如果都传入，以IotId为准）
     * @return
     */
    public Result BatchGetDeviceState(List<String> DeviceNames, String ProductKey, List<String> IotIds) {
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("BatchGetDeviceState");
        request.putQueryParameter("RegionId", regionId);
        if (DeviceNames != null) {
            for (int i = 0; i < DeviceNames.size(); i++) {
                request.putQueryParameter("DeviceName." + (i + 1), DeviceNames.get(i));
            }
        }
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        request.putQueryParameter("ProductKey", ProductKey);
        if (IotIds != null) {
            for (int i = 0; i < IotIds.size(); i++) {
                request.putQueryParameter("IotId." + (i + 1), IotIds.get(i));
            }
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    //设备影子相关API
    /**
     * 调用该接口查询指定设备的影子信息
     * @param DeviceName 要查询的设备名称
     * @param ProductKey 要查询的设备所隶属的产品的唯一标识
     * @return 调用成功时返回设备的影子信息
     */
    public Result GetDeviceShadow(String DeviceName,String ProductKey){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("GetDeviceShadow");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("DeviceName", DeviceName);
        request.putQueryParameter("ProductKey", ProductKey);
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }

    /**
     * 调用该接口修改指定设备的影子信息
     * @param DeviceName 要修改影子信息的设备名称
     * @param ProductKey 要修改影子的设备所隶属的产品的唯一标识
     * @param ShadowMessage 修改后设备的影子信息
     *                          影子信息参数中包含：
     *                          method：String，指定操作类型，取值：update。
     *                          state：String，发送给影子的具体状态，由desired参数表示期望的影子状态。
     *                          version：Long，设备影子的版本，必须大于当前影子版本。
     * @param DeltaUpdate 是否增量更新设备影子desired参数
     * @return
     */
    public Result UpdateDeviceShadow(String DeviceName,String ProductKey,String ShadowMessage,Boolean DeltaUpdate){
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("iot.cn-shanghai.aliyuncs.com");
        request.setSysVersion(sysVersion);
        request.setSysAction("UpdateDeviceShadow");
        request.putQueryParameter("RegionId", regionId);
        request.putQueryParameter("DeviceName", DeviceName);
        request.putQueryParameter("ProductKey", ProductKey);
        request.putQueryParameter("ShadowMessage", ShadowMessage);
        request.putQueryParameter("IotInstanceId", iotInstanceId);
        request.putQueryParameter("DeltaUpdate", DeltaUpdate.toString());

        try {
            CommonResponse response = client.getCommonResponse(request);
            return ResultHandler.dataResultHandler(response.getData());
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error("阿里云底层处理错误");
    }
}